const app = getApp()
const i18n = require('../../utils/i18n/index')

Page({
  data: {
    userInfo: null,
    isLogin: false,
    cdnUrl: '',
    locale: 'zh_CN',
    t: {}
  },

  onLoad() {
    this.setData({
      cdnUrl: app.globalData.cdnUrl
    })
    this.setI18nData()
    this.checkLogin()

    // 监听语言变更事件
    const self = this
    app.globalData.eventBus.on('localeChanged', function() {
      self.setI18nData()
    })
  },

  onShow() {
     // 更新导航栏标题
    wx.setNavigationBarTitle({
        title: i18n.getLocale()=='en_US'?'Mine':'个人中心'
    }); 
    // 延迟100ms，确保navigateBack后token已写入
    setTimeout(() => {
      const token = wx.getStorageSync('token')
      if (token) {
        app.globalData.token = token
        app.globalData.isLogin = true
        this.setData({ isLogin: true })
        this.loadUserInfo()
      } else {
        app.globalData.token = ''
        app.globalData.isLogin = false
        this.setData({ isLogin: false, userInfo: null })
      }
      if (typeof this.getTabBar === 'function' &&
          this.getTabBar()) {
        this.getTabBar().setData({
          selected: 2
        })
      }
    }, 100)
  },

  setI18nData() {
    this.setData({
      locale: i18n.getLocale(),
      t: {
        title: i18n.t('mine.title'),
        notLogin: i18n.t('mine.notLogin'),
        login: i18n.t('mine.loginGo'),
        notSetName: i18n.t('mine.notSetName'),
        notSetCompany: i18n.t('mine.notSetCompany'),
        menu: {
          mySupply: i18n.t('mine.menu.mySupply'),
          myInterest: i18n.t('mine.menu.myInterest'),
          settings: i18n.t('mine.menu.settings'),
          logout: i18n.t('mine.menu.logout')
        }
      }
    })
  },

  onLanguageChange() {
    this.setI18nData()
  },

  // 检查登录状态
  checkLogin() {
    const token = wx.getStorageSync('token')
    if (token) {
      app.globalData.token = token
      app.globalData.isLogin = true
      this.setData({ isLogin: true })
      this.loadUserInfo()
    }
  },

  // 加载用户信息
  loadUserInfo() {
    wx.request({
      url: app.globalData.baseUrl + 'api/user-info',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: res => {
        if (res.statusCode == 401) {
            this.onLogout()
        }
        if (res.data.code === 0) {
          this.setData({
            userInfo: res.data.data.user
          })
        }
      }
    })
  },

  // 登录处理
  onLogin() {
    wx.navigateTo({
      url: '/pages/mine/login/login'
    })
    return
    wx.login({
      success: res => {
        if (res.code) {
          wx.request({
            url: app.globalData.baseUrl + 'auth/login',
            method: 'POST',
            data: {
              code: res.code
            },
            success: loginRes => {
              if (loginRes.data.code === 0) {
                const token = loginRes.data.data.token
                wx.setStorageSync('token', token)
                app.globalData.token = token
                app.globalData.isLogin = true
                this.setData({ isLogin: true })
                this.loadUserInfo()
              }
            }
          })
        }
      }
    })
  },

  // 菜单项点击
  onMenuTap(e) {
    if (!this.data.isLogin) {
      wx.showToast({
        title: this.data.t.notLogin,
        icon: 'none'
      })
      return
    }

    const { type } = e.currentTarget.dataset
    switch (type) {
      case 'mySupply':
        wx.navigateTo({
          url: '/pages/supply/my/my'
        })
        break
      case 'myInterest':
        wx.navigateTo({
          url: '/pages/supply/interest/interest'
        })
        break
      case 'settings':
        wx.navigateTo({
          url: '/pages/mine/profile/profile'
        })
        break
    }
  },

  // 编辑资料
  onEditProfile() {
    if (!this.data.isLogin) {
      wx.showToast({
        title: this.data.t.notLogin,
        icon: 'none'
      })
      return
    }
    wx.navigateTo({
      url: '/pages/mine/profile/profile'
    })
  },

  // 加入大联盟
  onJoinTap() {
    if (!this.data.isLogin) {
      wx.showModal({
        title: '提示',
        content: '请先登录后再操作',
        success: (res) => {
          if (res.confirm) {
            this.onLogin()
          }
        }
      })
      return
    }
    wx.navigateTo({
      url: '/pages/mine/join/join'
    })
  },

  // 我的发布
  onMyPublishTap() {
    if (!this.data.isLogin) {
      wx.showModal({
        title: '提示',
        content: '请先登录后再操作',
        success: (res) => {
          if (res.confirm) {
            this.onLogin()
          }
        }
      })
      return
    }
    wx.navigateTo({
      url: '/pages/mine/publish/list'
    })
  },

  // 我的感兴趣
  onMyInterestTap() {
    if (!this.data.isLogin) {
      wx.showModal({
        title: '提示',
        content: '请先登录后再操作',
        success: (res) => {
          if (res.confirm) {
            this.onLogin()
          }
        }
      })
      return
    }
    wx.navigateTo({
      url: '/pages/mine/interest/list'
    })
  },

  // 注销
  onLogout() {
    wx.removeStorageSync('token')
    app.globalData.token = ''
    app.globalData.isLogin = false
    this.setData({
      isLogin: false,
      userInfo: null
    })
    wx.showToast({
      title: this.data.t.logoutSuccess || '已退出',
      icon: 'success'
    })
  }
}) 